import type { UserInfo } from "@/stores/user";

// 获取微信登录 code
export const getWxLoginCode = (): Promise<string> => {
  return new Promise((resolve, reject) => {
    uni.login({
      success: (res) => {
        if (res.code) {
          resolve(res.code);
        } else {
          reject(new Error("获取code失败"));
        }
      },
      fail: reject,
    });
  });
};

// 获取用户信息
export const getUserProfile = (): Promise<UserInfo> => {
  return new Promise((resolve, reject) => {
    uni.getUserProfile({
      desc: "用于完善会员资料",
      success: (res: any) => {
        const userInfo: UserInfo = {
          nickName: res.userInfo.nickName,
          avatar: res.userInfo.avatarUrl,
          sex: Number(res.userInfo.gender) || 0,
          phone: "13211111111",
        };
        resolve(userInfo);
      },
      fail: reject,
    });
  });
};

// 自动登录
export const autoLogin = async () => {
  try {
    const code = await getWxLoginCode();
    // 这里不需要用户信息，直接用code登录
    return { code };
  } catch (error) {
    console.error("自动登录失败：", error);
    throw error;
  }
};

// 登录流程
export const handleLogin = async () => {
  try {
    const userInfo = await getUserProfile();
    const code = await getWxLoginCode();
    return {
      userInfo,
      code,
    };
  } catch (error) {
    console.error("登录失败：", error);
    throw error;
  }
};
